<template>
  <div class="canvas">
    <canvas ref="myCanvas" :width="canvasWidth" :height="canvasHeight"></canvas>

    <span class="canvas-name">{{ getCurrentMapName }}</span>
  </div>
</template>

<script>
import common from "@/mixins/common";
import { mapGetters } from "vuex";
export default {
  mixins: [common],
  data() {
    return {
      // 定义变量，设置画布的宽度和高度
      canvasWidth: 800,
      canvasHeight: 600,
    };
  },
  computed: {
    ...mapGetters("map", ["getMapData", "getCurrentId", "getCurrentMapName"]),
  },
  mounted() {
    // 获取可视区域的宽度
    this.canvasWidth = document.documentElement.clientWidth;
    // 获取可视区域的高度
    this.canvasHeight = document.documentElement.clientHeight - 10;
    this.init();
    // 为 canvas 添加点击事件监听
    this.$refs.myCanvas.addEventListener("click", this.handleCanvasClick);
    this.$refs.myCanvas.style.cursor = "pointer";
  },
  methods: {
    init() {
      // 获取 canvas 元素和 2D 绘图上下文
      const canvas = this.$refs.myCanvas;
      const ctx = canvas.getContext("2d");

      // 建立全局地图及当前地图id
      this.setMapData(this.getMapData, this.getCurrentId);
      // 设置上下左右箭头
      this.setArrow(ctx, this.canvasWidth, this.canvasHeight);
      // 通知父组件添加相应图片
      this.$emit("addContent", ctx);
    },
    // 处理画布点击事件的方法
    handleCanvasClick(event) {
      const canvas = this.$refs.myCanvas;
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      // 父组件添加相应点击事件判断
      this.$emit("canvasClick", x, y);
      // 监听箭头点击事件
      this.inspectArrow(x, y, this.canvasWidth, this.canvasHeight);
    },
  },
  beforeDestroy() {
    // 移除事件监听，避免内存泄漏
    this.$refs.myCanvas.removeEventListener("click", this.handleCanvasClick);
  },
};
</script>

<style lang="scss" scoped>
canvas {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.canvas-name {
  position: absolute;
  bottom: 13px;
  left: 0;
}
</style>
